package com.example.seakdreamandroid.myInfo;

import static com.example.seakdreamandroid.Constant.BASE_URL;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.sleepRecord.SleepRecordActivity;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyInfo extends AppCompatActivity {
    private ImageView headshot;
    private File myhead;
    private Uri myUri;
    private byte[] bs;
    private byte[] data;
    private String res;
    private String headshot1;
    User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_info);
        headshot = findViewById(R.id.img_head_short);
        CameraActivity.setClipRatio(1, 1);

        headshot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setHeadshot();
            }
        });
        user=(User) getApplication();
        setfirst();

    }
    public void setHeadshot(){

        final String[] items3 = new String[]{"从相机拍摄", "从相册选择"};//创建item
        AlertDialog alertDialog3 = new AlertDialog.Builder(this)
                .setTitle("选择方式")
                .setIcon(R.mipmap.ic_launcher)
                .setItems(items3, new DialogInterface.OnClickListener() {//添加列表
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (i==0){
                            startActivity(new Intent(MyInfo.this, CameraActivity.class).putExtra(CameraActivity.ExtraType, CameraActivity.CAMERA));
                        }else {
                            startActivity(new Intent(MyInfo.this, CameraActivity.class).putExtra(CameraActivity.ExtraType, CameraActivity.PHOTO));
                        }
                    }
                })
                .create();
        alertDialog3.show();

    }
    @Override
    protected void onResume() {
        super.onResume();
        //获得相册、相机返回的结果，并显示
        if (CameraActivity.LISTENING) {
            Log.e("TAG", "返回的Uri结果：" + CameraActivity.IMG_URI);
            Log.e("TAG", "返回的File结果：" + CameraActivity.IMG_File.getPath());
            CameraActivity.LISTENING = false;   //关闭获取结果
            data = null;
            // 读取图片字节数组
            try {
                InputStream in = new FileInputStream(CameraActivity.IMG_File.getPath());
                data = new byte[in.available()];
                in.read(data);
                in.close();
            }catch (IOException e) {
                e.printStackTrace();
            }

            res = Base64.encodeToString(data,Base64.DEFAULT);
            setMyhead();



            Glide.with(this).load(CameraActivity.IMG_URI).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headshot);
             //显示图片到控件
        }
    }

    private void setfirst(){

        //2.创建请求对象（Request）,不需要设置请求体
        Request request = new Request.Builder()
                //设置请求的地址，默认的请求方式是Get请求
                .url(BASE_URL+"UserInfo/getUserInfo"+"?id="+user.getUserId())
                //创建Request对象
                .build();
        //3.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        //发起异步的请求，不需要手动创建子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //请求失败时回调
                Log.e("OkHttp","onFailure");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功时回调
                String reslut = response.body().string();
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            JSONObject object = new JSONObject(reslut);
                            JSONObject data = object.getJSONObject("data");
                            headshot1 = data.getString("headshot");

                            if(headshot!=null){
                                bs= Base64.decode(headshot1,Base64.DEFAULT);
                                for (int i = 0; i < bs.length; ++i) {
                                    if (bs[i] < 0) {
                                        bs[i] += 256;
                                    }
                                }
                                String time = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
                                String fileName = time;
                                myhead = new File(Environment.getExternalStorageDirectory()+"/my_head/",fileName+".jpg");
                                if (!myhead.getParentFile().exists()) {
                                    myhead.getParentFile().mkdirs();
                                }
                                FileOutputStream outputStream = null;
                                // 创建BufferedOutputStream对象
                                BufferedOutputStream bufferedOutputStream = null;
                                try {
                                    // 如果文件存在则删除
                                    // 获取FileOutputStream对象
                                    outputStream = new FileOutputStream(myhead);
                                    // 获取BufferedOutputStream对象
                                    bufferedOutputStream = new BufferedOutputStream(outputStream);
                                    // 往文件所在的缓冲输出流中写byte数据
                                    bufferedOutputStream.write(bs);
                                    // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
                                    bufferedOutputStream.flush();
                                } catch (Exception e) {
                                    // 打印异常信息
                                    e.printStackTrace();
                                } finally {
                                    // 关闭创建的流对象
                                    if (outputStream != null) {
                                        try {
                                            outputStream.close();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    if (bufferedOutputStream != null) {
                                        try {
                                            bufferedOutputStream.close();
                                        } catch (Exception e2) {
                                            e2.printStackTrace();
                                        }
                                    }
                                }
                                myUri = Uri.fromFile(myhead);
                                Glide.with(MyInfo.this).load(myUri).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(headshot);
                            }

                        }catch (Exception e){
                            e.printStackTrace();
                        }//setview
                    }
                });


            }
        });


    }

    private void setMyhead(){
        //2.创建请求体对象（FromBody）
        FormBody body = new FormBody.Builder()
                .add("userId",user.getUserId())
                .add("headshot",res)
                .build();
        //3.创建请求对象（Request）
        Request request = new Request.Builder()
                //设置
                .url(Constant.BASE_URL + "UserInfo"+"/setHeadshot")
                .post(body)//设置请求方式为POST，添加了请求体
                //创建Request对象
                .build();
        //4.发送请求，获取响应
        OkHttpClient okHttpClient = new OkHttpClient();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OkHttp","onFailure");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("OkHttp","请求成功");
                Log.e("响应码",response.code()+"");
                Log.e("响应体",response.body().string());
                Log.e("当前线程",Thread.currentThread().getName());
                //修改用户界面，需要使用Handler或者runOnUiThread
            }
        });
    }


}
